/**
 * @description 路由守卫，目前两种模式：all模式与intelligence模式
 */
import VabProgress from "nprogress";
import "nprogress/nprogress.css";
import type { Router } from "vue-router";
import {
  authentication,
  routesWhiteList,
  supportVisit,
} from "/@/config";
import { useRoutesStore } from "/@/store/modules/routes";
import { useSettingsStore } from "/@/store/modules/settings";
import { useUserStore } from "/@/store/modules/user";
import getPageTitle from "/@/utils/pageTitle";
import { toLoginRoute } from "/@/utils/routes";

// 用于判断登录页接口错误重试次数限制，防止进入循环跳转登陆界面
const retryTimes = 5;
let routerFlag = true;
let routerNum = 1;
export const setupPermissions = (router: Router) => {
  VabProgress.configure({
    easing: "ease",
    speed: 500,
    trickleSpeed: 200,
    showSpinner: false,
  });
  router.beforeEach(async (to, from, next) => {
    const {
      getTheme: { showProgressBar },
    } = useSettingsStore();
    // console.log(router.options.routes);
    const { routes, setRoutes } = useRoutesStore();
    const { token, getUserInfo} = useUserStore();
    if (showProgressBar) VabProgress.start();

    let hasToken = token;

    if (hasToken) {
      if (routes.length > 0) {
        // 禁止已登录用户返回登录页
        if (to.path === "/login") {
          next({ path: "/" });
          if (showProgressBar) VabProgress.done();
        } else {
          next();
        }
      } else {
        try {
          if (routerFlag) routerNum = 1;
          if (routesWhiteList.includes(to.path)) {
            next();
          } else {
            const flag = await setRoutes();
            if (!flag) {
              routerFlag = false;
              routerNum += 1;
            }
            let path =
              to.redirectedFrom && to.path == "/404"
                ? to.redirectedFrom.path
                : to.path;
            if (!flag && routerNum >= retryTimes) {
              next({path: "/500", replace: true});
            } else {
              if(flag) routerFlag = true;
              next({ path: path,query: to.query, replace: true });
            }
          }
        } catch (error) {
          // await resetAll();
          next(toLoginRoute(to.fullPath));
        }
      }
    } else {
     if (routesWhiteList.includes(to.path)) {
        next();
      } else {
        next(toLoginRoute(to.fullPath));
      }
    }
  });
  router.afterEach((to) => {
    if (typeof to.meta.title === "string")
      document.title = getPageTitle(to.meta.title);
    if (VabProgress.status) VabProgress.done();
  });

  router.onError((error: any) => {
    console.error(" 错误拦截:", error.message);
  });

  return router;
};
